import tetlib_py as tetlib
import sys

globaloptlist = "searchpath={{./} {./resource/cmap}}"

basedocoptlist = ""

# page-specific option list */
# Remove the tetml= option if you don't need font and geometry information
pageoptlist = "granularity=word tetml={glyphdetails={all}}"

def parse_document(document):
    try:
        try:
            pageno = 0
            tet = tetlib.TET_new()
    
            tetlib.TET_set_option(tet, globaloptlist)
            
            docoptlist =  "tetml={} %s" % basedocoptlist
            
            tetlib.TET_create_pvf(tet,"document.pdf",document,"")
            doc = tetlib.TET_open_document(tet, "document.pdf", docoptlist)
    
            if (doc == -1):
                raise Exception("Error %d in %s(): %s" % \
                   (tetlib.TET_get_errnum(tet), tetlib.TET_get_apiname(tet), tetlib.TET_get_errmsg(tet)))
    
            n_pages = int(tetlib.TET_pcos_get_number(tet, doc, "length:pages"))
    
            # loop over pages in the document */
            for pageno in range(1, n_pages+1):
                tetlib.TET_process_page(tet, doc, pageno, pageoptlist)
    
            # This could be combined with the last page-related call */
            tetlib.TET_process_page(tet, doc, 0, "tetml={trailer}")
    
            tetml = tetlib.TET_get_xml_data(tet, doc, "")
            if (not tetml): raise Exception("tetml: couldn't retrieve XML data")
    
            tetlib.TET_close_document(tet, doc)
    
            return tetml
    
        except tetlib.TETlibException:
            print("TET exception occurred:\n[%d] %s: %s" %
                ((tetlib.TET_get_errnum(tet)), tetlib.TET_get_apiname(tet),  tetlib.TET_get_errmsg(tet)))
            
            return None
    
        except Exception, x:
            print("Exception occurred: %s" % x)
    
            return None
            
    finally:
        tetlib.TET_delete(tet)
